package com.jlf.core.annotation;

import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 领域的dao的辅助工具
 *
 * @author wujr
 * 2021/9/30
 * @version 1.0
 * 变更历史
 * [wujr 2021/9/30 1.0 新增]
 */
public class DomainRepository {
    private static final List<String> _domainSuffix = Arrays.asList("DO", "VO", "DTO");

    public static String domainCode(Class<?> domainClass){
        String code = domainClass.getSimpleName();
        for (String suffix : _domainSuffix){
            if (code.endsWith(suffix)){
                return StringUtils.uncapitalize(code.substring(0, code.length() - suffix.length()));
            }
        }
        return StringUtils.uncapitalize(code);
    }
    public static String domainClassName(Class<?> domainClass){
        String className = domainClass.getSimpleName();
        for (String suffix : _domainSuffix){
            if (className.endsWith(suffix)){
                return className.substring(0, className.length() - suffix.length());
            }
        }
        return className;
    }
    @FunctionalInterface
    public static interface Visitor{
        /**
         * 访问领域模型
         * @param domainClass 领域模型的类
         * @param domain 该类的领域表注解
         */
        void visit(Class<?> domainClass, Domain domain);
    }
    /**
     * 持久化dao映射的领域名称
     * key：Dao的类
     * value：{@link Domain#name()}
     */
    private static final ConcurrentHashMap<Class<?>, String> _mapDaoOfDomains = new ConcurrentHashMap<>();
    /**
     * 领域的类映射的领域注解
     * key：领域的类
     * value：该领域的{@link Domain}注解
     */
    private static final ConcurrentHashMap<Class<?>, Domain> _mapAnnotationOfDomains = new ConcurrentHashMap<>();

    public static void add(Class<?> clazz, String domainName){
        _mapDaoOfDomains.put(clazz, domainName);
    }
    public static void add(Class<?> clazz, Domain annotation){
        _mapAnnotationOfDomains.put(clazz, annotation);
    }
    public static String name(Class<?> clazz){
        return _mapDaoOfDomains.get(clazz);
    }
    public static Domain annotation(Class<?> clazz){
        return _mapAnnotationOfDomains.get(clazz);
    }
    public static void visitDomain(Visitor visitor){
        _mapAnnotationOfDomains.forEach(visitor::visit);
    }
}
